<?php
// +----------------------------------------------------------------------
//            -------------------------
//           /   / ----------------\  \
//          /   /             \  \
//         /   /              /  /
//        /   /    /-------------- /  /
//       /   /    /-------------------\  \
//      /   /                   \  \
//     /   /                     \  \
//    /   /                      /  /
//   /   /      /----------------------- /  /
//  /-----/      /---------------------------/
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://baimifan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: Sage 2016/4/19  14:05
// +----------------------------------------------------------------------
namespace Wechat\Controller;
use Think\Controller;
use Common\Model\PayModel;
require_once COMMON_PATH . 'WxpayAPI/lib/WxPay.Api.php';
require_once COMMON_PATH . 'WxpayAPI/lib/WxPay.Data.php';

//支付中心
Class PayController extends Controller {
    function index() {
        $this->display();
    }
    //异步通知模块通用 pay_id
    //活动订单支付回调
    function notify_activity() {
        $xml = $GLOBALS["HTTP_RAW_POST_DATA"];
        //$xml='<xml><appid><![CDATA[wxc381b6c916cd12e0]]></appid><attach><![CDATA[80]]></attach><bank_type><![CDATA[CFT]]></bank_type><cash_fee><![CDATA[1]]></cash_fee><fee_type><![CDATA[CNY]]></fee_type><is_subscribe><![CDATA[Y]]></is_subscribe><mch_id><![CDATA[1243290602]]></mch_id><nonce_str><![CDATA[0phy8xbkios6l9qurbp9hcce1jshzt36]]></nonce_str><openid><![CDATA[ox2RwuFssQayIDaGlbpOJppnTyb4]]></openid><out_trade_no><![CDATA[124329060220160413114204]]></out_trade_no><result_code><![CDATA[SUCCESS]]></result_code><return_code><![CDATA[SUCCESS]]></return_code><sign><![CDATA[2D5A5D219A2AB68E53C995E4A30874C3]]></sign><time_end><![CDATA[20160413114210]]></time_end><total_fee>1</total_fee><trade_type><![CDATA[JSAPI]]></trade_type><transaction_id><![CDATA[4000852001201604134792628797]]></transaction_id></xml>';
        $postarr = (array)simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $DObj = new \WxPayResults();
        $DObj->FromArray($postarr);
        $ReplyObj = new \WxPayNotifyReply();
        $DData = $DObj->GetValues();
        $attach = json_decode($DData["attach"]); //业务数据
        $pay_real=$DData["cash_fee"]/100;//实际支付金额,
        //检查返回状态
        if ($DData['return_code'] != "SUCCESS") {
            $ReplyObj->SetReturn_code("ERROR");
            echo json_encode($ReplyObj->GetValues());
            exit();
        }
        //检查支付状态
        //支付未成功
        if ($DData['result_code'] != "SUCCESS") {
            $ReplyObj->SetReturn_code("SUCCESS");
            echo json_encode($ReplyObj->GetValues());
            exit();
        }
        //支付成功后业务处理
        //支付状态更改
        $pay_id = $attach->pay_id;
        $Pay = M("Pay");
        $dp = $Pay->where("pay_id=$pay_id")->find();
        if ($dp["status"] == 1) {
            //返回结果-已支付不做处理
            $ReplyObj->SetReturn_code("SUCCESS");
            echo json_encode($ReplyObj->GetValues());
            exit();
        }
        $Pay->startTrans();
        $data1['status'] = 1;
        $data1['money_real'] = $pay_real;
        $Pay->where("pay_id=$pay_id")->data($data1)->save();
        $dp = $Pay->where("pay_id=$pay_id")->find();
        if ($dp["status"] == 1) {
            $Pay->commit();
        } else {
            $Pay->rollback();
            exit();
        }
        //更改剩余报名人数量
        $Activityapply = M("Activity_apply");
        $dapp = $Activityapply->where("pay_id=$pay_id")->field("activity_id,is_applyfree,user_id")->find();
        $activity_id = $dapp["activity_id"];
        $Activity = M("Activity");
        $Activity->where("activity_id=$activity_id")->setDec("apply_num");
        //根据是否免报名费，更改当前会员卡的免报名费次数
        if ($dapp['is_applyfree'] == "1") {
            $num_deduct = $Activity->where("activity_id=$activity_id")->getField('num_deduct');
            $Card = M("Card");
            $Card->where("user_id=" . $dapp["user_id"])->setDec("num_activity",$num_deduct);
        }
        //积分增加
        $Score = D("Score");
        $Score->addscore($dapp['user_id'], "4");
        //返回结果
        $ReplyObj->SetReturn_code("SUCCESS");
        echo json_encode($ReplyObj->GetValues());
        exit();
    }

    //无报名费情况下，完成订单
    function fulfill_activity(){
        //支付成功后业务处理
        //支付状态更改
        $pay_id = I("post.pay_id");
        $Pay = M("Pay");
        $Pay->startTrans();

        $Pay->where("pay_id=$pay_id")->data(['status'=>1])->save();
        $dp = $Pay->where("pay_id=$pay_id")->find();
        if ($dp["status"] == 1) {
            $Pay->commit();
        } else {
            $Pay->rollback();
            exit();
        }
        //更改剩余报名人数量
        $Activityapply = M("Activity_apply");
        $dapp = $Activityapply->where("pay_id=$pay_id")->field("activity_id,is_applyfree,user_id")->find();
        $activity_id = $dapp["activity_id"];
        $Activity = M("Activity");
        $Activity->where("activity_id=$activity_id")->setDec("apply_num");
        //根据是否免报名费，更改当前会员卡的免报名费次数
        if ($dapp['is_applyfree'] == "1") {
            $num_deduct = $Activity->where("activity_id=$activity_id")->getField('num_deduct');
            $Card = M("Card");
            $Card->where("user_id=" . $dapp["user_id"])->setDec("num_activity",$num_deduct);
        }
        //积分增加
        $Score = D("Score");
        $Score->addscore($dapp['user_id'], "4");
        exit();
    }

    //借阅订单支付回调
    function notify_rent() {
        $xml = $GLOBALS["HTTP_RAW_POST_DATA"];
        //$xml='<xml><appid><![CDATA[wxc381b6c916cd12e0]]></appid><attach><![CDATA[80]]></attach><bank_type><![CDATA[CFT]]></bank_type><cash_fee><![CDATA[1]]></cash_fee><fee_type><![CDATA[CNY]]></fee_type><is_subscribe><![CDATA[Y]]></is_subscribe><mch_id><![CDATA[1243290602]]></mch_id><nonce_str><![CDATA[0phy8xbkios6l9qurbp9hcce1jshzt36]]></nonce_str><openid><![CDATA[ox2RwuFssQayIDaGlbpOJppnTyb4]]></openid><out_trade_no><![CDATA[124329060220160413114204]]></out_trade_no><result_code><![CDATA[SUCCESS]]></result_code><return_code><![CDATA[SUCCESS]]></return_code><sign><![CDATA[2D5A5D219A2AB68E53C995E4A30874C3]]></sign><time_end><![CDATA[20160413114210]]></time_end><total_fee>1</total_fee><trade_type><![CDATA[JSAPI]]></trade_type><transaction_id><![CDATA[4000852001201604134792628797]]></transaction_id></xml>';
        $postarr = (array)simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $DObj = new \WxPayResults();
        $DObj->FromArray($postarr);
        $ReplyObj = new \WxPayNotifyReply();
        $DData = $DObj->GetValues();
        $attach = json_decode($DData["attach"]); //业务数据
        $pay_real=$DData["cash_fee"]/100;//实际支付金额,
        //检查返回状态
        if ($DData['return_code'] != "SUCCESS") {
            $ReplyObj->SetReturn_code("ERROR");
            echo json_encode($ReplyObj->GetValues());
            exit();
        }
        //检查支付状态
        //支付未成功
        if ($DData['result_code'] != "SUCCESS") {
            $ReplyObj->SetReturn_code("SUCCESS");
            echo json_encode($ReplyObj->GetValues());
            exit();
        }
        //支付成功后业务处理
        //支付状态更改
        $Pay=new PayModel();
        if($Pay->complete_rent($attach->pay_id,$pay_real)){
            //返回结果
            $ReplyObj->SetReturn_code("SUCCESS");
            echo json_encode($ReplyObj->GetValues());
            exit();
        }else{

        }

    }

    //购书订单支付回调
    function notify_buy() {
        $xml = $GLOBALS["HTTP_RAW_POST_DATA"];
        //$xml='<xml><appid><![CDATA[wxc381b6c916cd12e0]]></appid><attach><![CDATA[80]]></attach><bank_type><![CDATA[CFT]]></bank_type><cash_fee><![CDATA[1]]></cash_fee><fee_type><![CDATA[CNY]]></fee_type><is_subscribe><![CDATA[Y]]></is_subscribe><mch_id><![CDATA[1243290602]]></mch_id><nonce_str><![CDATA[0phy8xbkios6l9qurbp9hcce1jshzt36]]></nonce_str><openid><![CDATA[ox2RwuFssQayIDaGlbpOJppnTyb4]]></openid><out_trade_no><![CDATA[124329060220160413114204]]></out_trade_no><result_code><![CDATA[SUCCESS]]></result_code><return_code><![CDATA[SUCCESS]]></return_code><sign><![CDATA[2D5A5D219A2AB68E53C995E4A30874C3]]></sign><time_end><![CDATA[20160413114210]]></time_end><total_fee>1</total_fee><trade_type><![CDATA[JSAPI]]></trade_type><transaction_id><![CDATA[4000852001201604134792628797]]></transaction_id></xml>';
        $postarr = (array)simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $DObj = new \WxPayResults();
        $DObj->FromArray($postarr);
        $ReplyObj = new \WxPayNotifyReply();
        $DData = $DObj->GetValues();
        $attach = json_decode($DData["attach"]); //业务数据
        $pay_real=$DData["cash_fee"]/100;//实际支付金额,
        //检查返回状态
        if ($DData['return_code'] != "SUCCESS") {
            $ReplyObj->SetReturn_code("ERROR");
            echo json_encode($ReplyObj->GetValues());
            exit();
        }
        //检查支付状态
        //支付未成功
        if ($DData['result_code'] != "SUCCESS") {
            $ReplyObj->SetReturn_code("SUCCESS");
            echo json_encode($ReplyObj->GetValues());
            exit();
        }
        //支付成功后业务处理
        //支付状态更改
        //支付状态更改
        $Pay=new PayModel();
        if($Pay->complete_buy($attach->pay_id,$pay_real)){
            //返回结果
            // todo 按照图书数量增加积分
            $ReplyObj->SetReturn_code("SUCCESS");
            echo json_encode($ReplyObj->GetValues());
            exit();
        }else{

        }
    }

    //会员充值订单支付回调
    function notify_vip() {
        $xml = $GLOBALS["HTTP_RAW_POST_DATA"];
        //$xml='<xml><appid><![CDATA[wxc381b6c916cd12e0]]></appid><attach><![CDATA[80]]></attach><bank_type><![CDATA[CFT]]></bank_type><cash_fee><![CDATA[1]]></cash_fee><fee_type><![CDATA[CNY]]></fee_type><is_subscribe><![CDATA[Y]]></is_subscribe><mch_id><![CDATA[1243290602]]></mch_id><nonce_str><![CDATA[0phy8xbkios6l9qurbp9hcce1jshzt36]]></nonce_str><openid><![CDATA[ox2RwuFssQayIDaGlbpOJppnTyb4]]></openid><out_trade_no><![CDATA[124329060220160413114204]]></out_trade_no><result_code><![CDATA[SUCCESS]]></result_code><return_code><![CDATA[SUCCESS]]></return_code><sign><![CDATA[2D5A5D219A2AB68E53C995E4A30874C3]]></sign><time_end><![CDATA[20160413114210]]></time_end><total_fee>1</total_fee><trade_type><![CDATA[JSAPI]]></trade_type><transaction_id><![CDATA[4000852001201604134792628797]]></transaction_id></xml>';
        $postarr = (array)simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $DObj = new \WxPayResults();
        $DObj->FromArray($postarr);
        $ReplyObj = new \WxPayNotifyReply();
        $DData = $DObj->GetValues();
        $attach = json_decode($DData["attach"]); //业务数据
        $pay_real=$DData["cash_fee"]/100;//实际支付金额,
        //检查返回状态
        if ($DData['return_code'] != "SUCCESS") {
            $ReplyObj->SetReturn_code("ERROR");
            echo json_encode($ReplyObj->GetValues());
            exit();
        }
        //检查支付状态
        //支付未成功
        if ($DData['result_code'] != "SUCCESS") {
            $ReplyObj->SetReturn_code("SUCCESS");
            echo json_encode($ReplyObj->GetValues());
            exit();
        }
        //支付成功后业务处理
        //支付状态更改
        $pay_id = $attach->pay_id;
        $Pay = M("Pay");
        $dp = $Pay->where("pay_id=$pay_id")->find();
        if ($dp["status"] == 1) {
            //返回结果-已支付不做处理
            $ReplyObj->SetReturn_code("SUCCESS");
            echo json_encode($ReplyObj->GetValues());
            exit();
        }
        $Pay->startTrans();
        $data1['status'] = 1;
        $data1['money_real'] = $pay_real;
        $Pay->where("pay_id=$pay_id")->data($data1)->save();
        $dp = $Pay->where("pay_id=$pay_id")->find();
        if ($dp["status"] == 1) {
            $Pay->commit();
        } else {
            $Pay->rollback();
        }
        //更改延长会员期限
        $Deposit = M("View_deposit");
        $dde = $Deposit->where("pay_id=$pay_id")->find();
        $Card = M("Card");
        $dc = $Card->where("card_id=" . $dde['card_id'])->find();
        $newdata['create_time'] = date("Y-m-d h:i:s", time());
        if (strtotime($dc['expire_time']) < time()) {
            $newdata["expire_time"] = date("Y-m-d h:i:s", strtotime("+" . $dde["month"] . "months", time()));
        } else {
            $newdata["expire_time"] = date("Y-m-d h:i:s", strtotime("+" . $dde["month"] . "months", strtotime($dc['expire_time'])));
        }
        $newdata["num_activity"] = $dc["num_activity"] + $dde["num_activity"];
        $newdata["num_delivery"] = $dc["num_delivery"] + $dde["num_delivery"];
        if($dc['discount_buy']>$dde['discount_buy']){
            $newdata["discount_buy"] = $dde["discount_buy"];
        }
        if($dc['discount_apply']>$dde['discount_apply']){
            $newdata["discount_apply"] = $dde["discount_apply"];
        }
        $Card->where("card_id=" . $dde['card_id'])->data($newdata)->save();
        //返回结果
        $ReplyObj->SetReturn_code("SUCCESS");
        echo json_encode($ReplyObj->GetValues());
        exit();
    }
}